package group2.controller;

import group2.model.*;
import group2.service.IOrderIService;
import group2.service.IReceiveAddressService;
import group2.service.IShoppingCarService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 李显星
 * @date 2020/8/17 15:13
 **/
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    IOrderIService orderService;

    @Autowired
    IShoppingCarService shoppingCarService;

    @Autowired
    IReceiveAddressService receiveAddressService;

    /**
     * 添加订单
     * @param order
     * @return
     */
    @RequestMapping("/addOrder")
    @ResponseBody
    public Map<String,Object>  addOrder(OrderInfo order, HttpSession session){
            Map<String,Object> map = new HashMap<>();
        double totalPrice = 0;
        //获取用户购买的所有书籍
        List<BooksCar> buyBookList = this.shoppingCarService.findCarInfo(((UserInfo) session.getAttribute("loguser")).getUserId());

        //计算订单的总价
        for (BooksCar booksCar : buyBookList) {

            Double price = (double)booksCar.getBook().getPrice();
            totalPrice +=  booksCar.getBook().getPrice() * booksCar.getBook_num();

        }

        order.setTotal(totalPrice);
        /**
        order.setUserId(((UserInfo)session.getAttribute("userInfo")).getUserId());
        order.setAddress(((UserInfo)session.getAttribute("userInfo")).getAddress());
        order.setPhone(((UserInfo)session.getAttribute("userInfo")).getPhone());
         */
        UserInfo logUser = (UserInfo) session.getAttribute("loguser");
        ReceiveAddress receiveAddress = this.receiveAddressService.selectById(logUser.getUserId());
        order.setUserId(logUser.getUserId());
        order.setAddress(receiveAddress.getAddress());
        order.setPhone(receiveAddress.getPhone());

        //生成订单的状态默认是 ”待发货“
        order.setOrderStatus(2);

        //生成订单
        int i = this.orderService.addOrder(order);

        //通过创建时间查询最晚生成的订单编号
        String orderId = findOrderId();

        //生成订单详情
        Map<String, Object> resultMap = addOrderDetail(orderId,session);

        //从购物车删除本次购买的书籍信息
        int j = this.shoppingCarService.deleteAll(((UserInfo) session.getAttribute("loguser")).getUserId());

        if(i == 1){
            if (j != 0){
                //return resultCode("200","添加订单及订单详情成功，清空购物车成功");
                map.put("code","200");
                map.put("msg","添加订单及订单详情成功，清空购物车成功");

            }
            map.put("code","500");
            map.put("msg","添加订单及订单详情成功，清空购物车失败");
            //return resultCode("500","添加订单及订单详情成功，清空购物车失败");
        }
        map.put("code","500");
        map.put("msg","添加订单及订单详情失败");
       // return resultCode("500","添加订单及订单详情失败");
        return map;
    }


    /**
     * 添加订单详情
     * @param
     */
    public Map<String,Object> addOrderDetail(String orderId, HttpSession session){

        OrderDetail orderDetail = new OrderDetail();

        //获取用户购买的所有书籍
        List<BooksCar> buyBookList = this.shoppingCarService.findCarInfo(((UserInfo) session.getAttribute("loguser")).getUserId());

        int i = 0;
        //每本书对应一个订单详情，逐一添加订单详情
        for (BooksCar booksCar : buyBookList) {
            orderDetail.setBookId(booksCar.getBook_id());
            orderDetail.setNum(booksCar.getBook_num());
            orderDetail.setPrice(booksCar.getBook().getPrice());

            orderDetail.setOrderId(orderId);

            //添加订单详情
            i = this.orderService.addOrderDetail(orderDetail);
        }

        if(i == 1){
            return resultCode("200","添加订单详情成功");
        }
        return resultCode("500","添加订单详情失败");
    }


    /**
     * 查询所有订单
     * @return 订单列表
     */
    @RequestMapping("/findAll")
    public String findAll(HttpSession session){
        //将订单的创建时间格式化
        List<OrderInfo> orderList =  formatDate(this.orderService.findAll());
        session.setAttribute("orderList",orderList);
        return "redirect:/views/order-list.jsp";
    }

    /**
     * 查询进行中的订单
     * @return
     */
    @RequestMapping("/findOfProcessing")
    public String findOfProcessing(HttpSession session){
        List<OrderInfo> ProcessingList = formatDate(this.orderService.findOfProcessing());
        session.setAttribute("ProcessingList",ProcessingList);
        return "redirect:/views/order-ing.jsp";
    }


    /**
     * 查询已完成的订单
     * @return
     */
    @RequestMapping("/findOfFinish")
    public String findOfFinish(HttpSession session){
        List<OrderInfo> findList = formatDate(this.orderService.findOfFinish());
        session.setAttribute("findList",findList);
        return "redirect:/views/order-finish.jsp";
    }


    /**
     * 查询已取消的订单
     * @return
     */
    @RequestMapping("/findCancel")
    @ResponseBody
    public List<OrderInfo> findCancel(){
        return formatDate(this.orderService.findCancel());
    }


    /**
     * 按编号查询订单详情
     * @param orderId
     * @return
     */
    @RequestMapping("/findById")
    public String findById(@Param("orderId") String orderId,HttpSession session){
        List<OrderDetail> selectList=this.orderService.findOrderDetailById(orderId);
        session.setAttribute("selectList",selectList);
        return "redirect:/views/order-finish.jsp";
    }


    /**
     * 查询最晚生成的订单编号
     * @return
     */
    public String findOrderId(){
        return this.orderService.findOrderId();
    }


    /**
     * 取消订单
     * @param orderId
     */
    @RequestMapping("/cancel")
    @ResponseBody
    public Map<String,Object> cancelOrder(@Param("orderId") String orderId){
        int i = this.orderService.cancelOrder(orderId);

        if(i == 1){
            return resultCode("200","取消订单成功");
        }
        return resultCode("500","取消订单失败");
    }


    /**
     * 删除订单及对应的订单详情
     * @param orderId
     */
    @RequestMapping("/deleteOrder")
    @ResponseBody
    public Map<String,Object> delete(@Param("orderId") String orderId){
        int i = this.orderService.deleteOrder(orderId);

        if(i == 1){
            return resultCode("200","删除订单成功");
        }
        return resultCode("500","删除订单失败");
    }


    /**
     * 确认收货
     * @param orderId
     * @return
     */
    @RequestMapping("/confirmReceipt")
    @ResponseBody
    public Map<String,Object> confirmReceipt(@Param("orderDetail") String orderId){
        int i = this.orderService.confirmReceipt(orderId);

        if(i == 1){
            return resultCode("200","收货成功");
        }
        return resultCode("500","收货失败");
    }



    /**
     * 将添加或者删除操作的结果信息（成功或失败）添加到Map
     * @param code
     * @param message
     * @return
     */
    public static Map<String,Object> resultCode(String code, String message){

        HashMap<String, Object> resultMap = new HashMap<>();

        resultMap.put("code", code);
        resultMap.put("message", message);

        return resultMap;
    }


    /**
     * 将订单中的日期格式化
     * @param list
     * @return
     */
    public static List<OrderInfo> formatDate(List<OrderInfo> list){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (OrderInfo orderInfo : list) {
            orderInfo.setFormatTime(sdf.format(orderInfo.getCreateTime().getTime()));
        }
        return list;
    }



}
